<?php

//Widget Action
add_action('widgets_init', 'bc_register_widget');

function bc_register_widget() {
	register_widget('bc_widget');
}

class bc_widget extends WP_Widget {
	
	// Process the new widget
	function bc_widget() {
		$widget_ops = array(
			'classname' => 'bc_widget_class',
			'description' => 'Compare prices of books between online retailers.'
		);
		$this->WP_Widget( 'bc_widget', 'Book Compare', $widget_ops);
	}
	
	// Build the widget settings form
	function form($instance) {
		$defaults = array(
			'title' => '',
			'widget_isbn' => '',
			'custom_meta' => '',
			'amazon' => 'on',
			'half' => 'on',
			'chegg' => 'on',
			'images' => 'on',
			'image_size' => 'medium',
			'error' => ''
		);
		$instance = wp_parse_args( (array) $instance, $defaults );
		extract($instance);
		
		if(esc_attr($error) != '') {
			echo "<p>" . $error . "</p>";
		}
		
		?>
		<p>Title:<input class="widefat" name="<?php echo $this->get_field_name('title'); ?>"
			type="text" value="<?php echo esc_attr($title); ?>" /></p>
		<p>isbn (separated by comma) <input class="widefat" name="<?php echo $this->get_field_name('widget_isbn'); ?>"
			type="text" value="<?php echo esc_attr($widget_isbn); ?>" /></p>
		<p>Custom Post Meta <input class="widefat" name="<?php echo $this->get_field_name('custom_meta'); ?>"
			type="text" value="<?php echo esc_attr($custom_meta); ?>" /></p>
		<p>Show Images <input name="<?php echo $this->get_field_name( 'images' ); ?>" 
				type="checkbox" <?php checked($images, 'on'); ?> /></p>
		<p>Image Size 
			<select name="<?php echo $this->get_field_name( 'image_size' ); ?>" >
				<option value="Small" <?php if ( $image_size == 'Small' ) echo 'selected="selected"'; ?>>Small</option>
				<option value="Medium" <?php if ( $image_size == 'Medium' ) echo 'selected="selected"'; ?>>Medium</option>
				<option value="Large" <?php if ( $image_size == 'Large' ) echo 'selected="selected"'; ?>>Large</option>
			</select>
			
		<p>Compare:<p><br/>
		<p>Amazon <input name="<?php echo $this->get_field_name( 'amazon' ); ?>" 
				type="checkbox" <?php checked($amazon, 'on'); ?> /></p>
		<p>Half <input name="<?php echo $this->get_field_name( 'half' ); ?>" 
				type="checkbox" <?php checked($half, 'on'); ?> /></p>
		<p>Chegg <input name="<?php echo $this->get_field_name( 'chegg' ); ?>" 
				type="checkbox" <?php checked($chegg, 'on'); ?> /></p>
		<?php
	}
	
	// Update Widget
	function update($new_instance, $old_instance) {
		$instance = $old_instance;
		$instance['title'] = esc_attr($new_instance['title']);
		$instance['widget_isbn'] = esc_attr($new_instance['widget_isbn']);
		$instance['amazon'] = strip_tags($new_instance['amazon']);
		$instance['half'] = strip_tags($new_instance['half']);
		$instance['chegg'] = strip_tags($new_instance['chegg']);
		$instance['images'] = strip_tags($new_instance['images']);
		$instance['custom_meta'] = strip_tags($new_instance['custom_meta']);
		$instance['image_size'] = strip_tags($new_instance['image_size']);
		
		return $instance;
	}
	
	
	// Display the widget
	function widget($args, $instance) {
		extract($args);
		extract($instance);
		
		global $post;
		$post_id = $post->ID;
		
		// First Get all possible locations the isbn could be stored
		$isbn_meta_box = get_post_meta( $post_id, '_isbn_meta_box', true );
		$isbn_custom_meta = get_post_meta( $post_id, $custom_meta, true );
		$options = get_option( 'bc_options' );
		$default_keyword = $options['default_keyword'];
		
		// If isbn_meta is not empty display the widget
		if($isbn_meta_box != '') {
			bc_widget_constructor($isbn_meta_box, $args, $instance);
			echo "From Meta_box";
		}
		
		// If there is no isbn_meta then check for the defined post_meta term
		elseif ($isbn_custom_meta != '' ) {
			bc_widget_constructor($isbn_custom_meta, $args, $instance);
			echo "From Custom Meta";
		}
		
		// If there are isbns in widget use those.
		elseif( $widget_isbn != '' ) {
			bc_widget_constructor($widget_isbn, $args, $instance);
			echo "From the Widget ISBN";
		}
		
		// If there is a defualt isbn from the options page display that
		elseif ( $default_keyword != '' ) {
			bc_widget_constructor( $default_keyword, $args, $instance);
			echo "From the Options Page";
		}
		
		// If all else fails don't show anything
		else {
			echo "Nothing present!";
		}

	}
	
	
} // End Class bc_widget

// Gather the data from API's and print the widget
function bc_widget_constructor($bc_isbn, $args, $instance) {
	extract($instance);
	extract($args);

	$options = get_option( 'bc_options' );
	extract($options);
	
	// Gather Data From Amazon
	$bc_amazon_price = bc_amazon_price_gen($bc_isbn);

	if( $bc_amazon_price == false ) {
		echo "Something went wrong with: " . $bc_isbn . "<br />";
	}
	else {
		// Get the Rest of the Display Information
		$bc_amazon_details = bc_amazon_details_gen($bc_isbn);
		$bc_amazon_images = bc_amazon_image_gen($bc_isbn);

		// Extract all of the variables
		extract($bc_amazon_price);
		extract($bc_amazon_details);
		extract($bc_amazon_images);
		
		// If image is on from widget setting grab it
		if( $images == 'on' ) {
			if ($image_size == 'Small')
				$image_size = $SmallImage;
			elseif ($image_size == 'Large')
				$image_size = $LargeImage;
			else // Default
				$image_size = $MediumImage;
				
			$bc_image_widget = "<div class='bc_image'><a href='" . $DetailPageURL . "' target='_blank'><img src='" . $image_size . "' alt='" . $Title . "' /></a></div> ";
		}
		else
			$bc_image_widget = '';
			
		// Format $title
		if ($Title != '') 
			$Title = "<div class='bc_book_title'>" . $Title . "</div>";
		
		// Format $Author 
		if ($Author != '')
			$Author = "<div class='bc_book_author'>By: " . $Author . "</div>";
		
		// Format Amazon Price
		if( $amazon == 'on' ) {
			// Check to see which type of price I should be displaying
			if( isset($LowestCollectablePrice) and $price_display == 'LowestCollectablePrice')
				$bc_amazon_price = $LowestCollectablePrice;
			elseif( isset($LowestNewPrice) and $price_display == 'LowestNewPrice' )
				$bc_amazon_price = $LowestNewPrice;
			// Default -> LowestUsedPrice
			else { 
				if ($LowestUsedPrice == '' )
					$bc_amazon_price = '';
				else
					$bc_amazon_price = $LowestUsedPrice;
			}
			
			// Amazon Output
			$bc_amazon = "<div class='bc_price_box'>
							<div class='bc_price_title'>Amazon</div> 
							<div class='bc_price'>
								<a href='" . $DetailPageURL . "' target='_blank'>" . $bc_amazon_price . "</a>
							</div>
						</div>";
		}
		else 
			$bc_amazon = '';
		
		// Format Half Information
		if ($half == 'on') {
			$bc_half_info = bc_half_details_gen($bc_isbn);
			if ($bc_half_info != False) {
				$bc_half = "<div class='bc_price_box'>
								<div class='bc_price_title'>Half/eBay.com</div> 
								<div class='bc_price'>
									<a href='" . $bc_half_info['url'] . "' target='_blank'>" . $bc_half_info['price'] . "</a>
								</div>
							</div>";
			}
			else
				$bc_half = '';
		}
		else
			$bc_half = '';
		
		// Get all of the information from Commission Junction
		$bc_cj_details = bc_cj_price_gen($bc_isbn);
		$bc_cj = '';
		foreach ( $bc_cj_details as $key=>$value ) {
			$bc_cj .= "<div class='bc_price_box'>
							<div class='bc_price_title'>" . $key . "</div> 
							<div class='bc_price'>"
								. $value . "
							</div>
						</div>";
		}
		
		
		
		// Print the Widget
		echo $before_widget;
		echo $before_title . $title . $after_title;
		echo $bc_image_widget;
		echo $Title;
		echo $Author;
		echo "<div class='bc_prices'>";
		echo $bc_amazon;
		echo $bc_half;
		echo $bc_cj;
		echo "</div><!-- bc_prices -->";
		echo $after_widget; 
		echo "<div style='clear:both'></div>";

	}
}


?>